package ro.ubbcluj.cs.damate.managers.registration;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import ro.ubbcluj.cs.damate.managers.BaseView;
import ro.ubbcluj.cs.damate.persistence.entities.User;
import ro.ubbcluj.cs.damate.services.GroupService;
import ro.ubbcluj.cs.damate.services.UserService;
import ro.ubbcluj.cs.damate.services.mail.MailService;
import ro.ubbcluj.cs.damate.webutils.MessageProvider;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.ValidatorException;
import java.io.Serializable;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.regex.Pattern;

/**
 * @author Lóránd Fazakas (lorand)
 *         Date: 5/10/12
 *         Time: 11:37 PM
 */
@Component
@Scope("request")
public class RegistrationManager extends BaseView implements Serializable {

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;

    @Autowired
    private transient PasswordEncoder passwordEncoder;

    @Autowired
    private MailService mailService;

    private User newUser;

    private boolean success;

    public String signUpUser() {

        newUser.setPassword(passwordEncoder.encodePassword(newUser.getPassword(), null));
        newUser.setState(false);
        newUser.setRegistrationDate(new Date(System.currentTimeMillis()));
        newUser.setLastActive(new Timestamp(System.currentTimeMillis()));
        newUser.setGroup(groupService.findGroupByName("user"));

        userService.create(newUser);
        mailService.sendRegistrationConfirmation(newUser);
        this.success = true;
        return null;
    }

    public User getNewUser() {
        if (newUser == null) {
            newUser = new User();
        }
        return newUser;
    }

    public void setNewUser(User newUser) {
        this.newUser = newUser;
    }

    public boolean isSuccess() {
        return success;
    }
}
